import java.util.*;
import java.io.*;

class MoCrapBlend
{
    //Takes in four arguments:
    //arg[0] = input asf
    //arg[1] = input amc
    //arg[2] = input amc 2
    //arg[3] = output amc of blend
    public static void main(String[] args)
    {
        MoCrapBlend program = new MoCrapBlend();
        if (args.length != 4)
            program.fail("Wrong number of arguments.");
        AMCParser amcParser = new AMCParser();
        ASFParser asfParser = new ASFParser();
        asfParser.parseASF(args[0]);
        ArrayList<Bone> skeleton = asfParser.skeleton;
        ArrayList<Motion> motion = amcParser.parseFile(args[1]);
        for (int i = 0; i < motion.size(); i++)
        {
            String s = motion.get(i).name();
            int n = asfParser.searchBone(s, skeleton);
            motion.get(i).setLimits(skeleton.get(n).getLimits());
        }
        ArrayList<Motion> motion2 = amcParser.parseFile(args[2]);
        for (int i = 0; i < motion2.size(); i++)
        {
            String s = motion2.get(i).name();
            int n = asfParser.searchBone(s, skeleton);
            motion2.get(i).setLimits(skeleton.get(n).getLimits());
        }
        
        MatLabArray matArray = new MatLabArray("o1", motion.get(25).getWave(0));
        matArray.toFile("original1.m");
        matArray = new MatLabArray("o2", motion2.get(25).getWave(0));
        matArray.toFile("original2.m");
        
        motion = program.blend(motion, motion2); //does band equalizing
        
        for (int i = 0; i < motion.size(); i++)
            motion.get(i).updateLimits();
        
        amcParser.outputFile(motion, args[3]); //outputs new amc
        //25
        matArray = new MatLabArray("n", motion.get(25).getWave(0));
        matArray.toFile("new.m");
        
        
    }
    
    //blends equal amounts of m1 and m2 and returns blend
    ArrayList<Motion> blend(ArrayList<Motion> m1, ArrayList<Motion> m2)
    {
        for (int i = 0; i < m1.size(); i++)
        {
            if (m1.get(i).size() > m2.get(i).size())
                m1.get(i).trim(m2.get(i).size());
            if (m2.get(i).size() > m1.get(i).size())
                m2.get(i).trim(m1.get(i).size());
            m1.get(i).createPyramids();
            m2.get(i).createPyramids();
            for (int j = 0; j < m1.get(i).numWaves(); j++)
            {
                double[][] L2 = m2.get(i).getLaplacian(j);
                m1.get(i).addLaplacian(j, L2);
            }
            m1.get(i).reconstruct();
        }
        return m1;
    }
    
    
    
    void fail(String msg)
    {
        System.err.println("Error: " + msg);
        System.exit(1);
    }
}
